<!-- 质量报告反馈 -->
<template>
  <div>
    <TopFilter ref="TopFilters" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="110" @filterChange="changeHandle"></TopFilter>
    <!-- table -->
    <FilterTable ref="tables" :columns="columns" :params="fetchParams" :dataSource="dataList" :datakey="'records'" :fetchapi="fetchApi" :onColumnsChange="onColumnsChange" :onRowSelectChange="selectChange">
      <template slot="controls">
        <multiuse-button :isShow="isDLR" size="small" type="primary" :click="handleAdd">新增</multiuse-button>
        <multiuse-button size="small" type="primary" :click="exportFileBtn.bind()" plain>导出</multiuse-button>
      </template>
    </FilterTable>

    <!-- 弹窗详情表单 -->
    <Drawer :visible.sync="editVisible" :title="setEditFormTitle" destroyOnClose width="80%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <EditForm ref="editFormDom" @close="editClose" @refreshTable="refreshTable" @save="editSave" @handleAudit="handleAudit" :rowData='editData'></EditForm>
    </Drawer>

    <!--  车辆选择 -->
    <BaseDialog :visible.sync="isShowDialog.car" title="车辆选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <VehicleChoice @close="closeDialog('car')" @onConfirm="handleVehicleChoice" :vinOne="searchVin" />
    </BaseDialog>

    <!--  零件选择 -->
    <BaseDialog :visible.sync="isShowDialog.part" title="零件选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <PartChoice @close="closeDialog('part')" @onConfirm="handlePartChoice" />
    </BaseDialog>

    <img id="barcode" style="display: none" />
  </div>
</template>
<script>
import EditForm from '../common/components/EditForm.vue';
import VehicleChoice from '../common/components/VehicleChoice';
import PartChoice from '../common/components/PartChoice';
import moment from 'moment';
import QRcode from 'qrcode';
import { exportExcelFile } from '@/utils/index';
import { getPartType } from '@/api/dictionary/index.js';
import JsBarcode from 'jsbarcode';
import { dictionary } from '@/utils/dictMixin';
import { getAppId } from '@/assets/js/auth';
// 接口
import { reqList, reqExcel, reqSupName } from '@/api/serviceass/qualityManage/feedback';
// mock 方法
import mockFun from "@/mock/fun"
const { mockList } = mockFun.qualityManage.mockFunWrap() // 涉及闭包 所以需要先调用外层函数一次 然后通过解构获取对应mock方法

// 数据格式化
import { formatDataCarInfo, formatDataPartInfo } from '../format'
import { mapGetters, mapMutations } from 'vuex'
export default {
  name: 'qualityManage',
  mixins: [dictionary],
  components: {
    EditForm,
    VehicleChoice,
    PartChoice
  },
  props: {
    // 筛选条件 需要隐藏的字段名
    hideFilterStrArr: {
      type: Array,
      default: () => [''] // ['str1' , 'str2']
    },
  },
  data() {
    return {
      // 筛选条件数据源
      topFilterInit: this.topFilterInitFun(),
      // 列表数据源
      columns: this.creatHeader(),
      // 非单个禁用
      // single: true,
      single: false,
      // 非多个禁用
      multiple: true,
      dataList: [],
      editVisible: false,
      collapse: true,
      // fetchApi: mockList,//mock接口,
      fetchApi: reqList,
      fetchParams: {
        // returnType : 55851001,
        // applyBeginDate: moment()
        //   .month(moment().month())
        //   .startOf('month')
        //   .format('YYYY-MM-DD HH:mm:ss'),
        // applyEndDate: moment()
        //   .month(moment().month())
        //   .endOf('month')
        //   .format('YYYY-MM-DD HH:mm:ss'),
        /**
         * 设为 false， mock逻辑接口才可正常
         */
        xhrAbort: false
      }, //ipa 接口
      selectedRows: [], //选中经销商
      disableds: true,
      editData: {},// 当前编辑数据
      /**
       * 字段映射
       */
      statusMap: {
        DLR: {
          '50031001': 'edit',
          '50031004': 'edit',
        },
        OEM: {
          '50031001': 'audit',
        }
      },
      btnValueMap: {
        edit: '编辑',
        audit: '审核'
      }
    };
  },
  created() {
    /**
     * 默认为最近一周数据
     */
    // this.fetchParams.applyBeginDate = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
    // this.fetchParams.applyEndDate = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
  },
  computed: {
    ...mapGetters('qualityManage', ['pageType', 'editFormStatus', 'isShowDialog', 'searchVin', 'searchPartType']),
    isDLR() {
      return this.pageType === 'DLR'
    },
    /**
     * 弹窗标题
     */
    setEditFormTitle() {
      const { editFormStatus } = this;
      const valMap = {
        readonly: '',
        add: '新增',
        ...this.btnValueMap
      }
      return `${valMap[editFormStatus]}质量报告`
    },

  },
  methods: {
    ...mapMutations('qualityManage', ['SET_STATE_BY_NAME']),
    /**
     * 筛选条件配置
     */
    topFilterInitFun() {
      let data = [
        { type: 'INPUT', label: '质量报告单号', fieldName: 'reportNo', placeholder: '请输入质量报告单号', initialValue: '' },
        { type: 'INPUT', label: 'VIN', fieldName: 'vin', placeholder: '请输入VIN', initialValue: '' },
        {
          type: 'RANGE_DATE',
          label: '报告时间',
          fieldName: 'applyBeginDate|applyEndDate',
          placeholder: '请选择日期',
          initialValue: '',
          rules: [{ required: false, message: '请选择日期', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'reportStatus',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('5003')
        },
        { type: 'INPUT', label: '服务中心', fieldName: 'dealerName', placeholder: '请输入服务中心名称', initialValue: '' }
      ];

      // 过滤需要隐藏的筛选条件
      data = data.filter(item => !this.hideFilterStrArr.includes(item.fieldName));
      return data;
    },
    /**
     * table表头和数据源
     */
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          align: 'center',
          render: props => {
            const { getBtnValue, chooseOrderNo } = this
            const btnVal = getBtnValue(props.row)
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => chooseOrderNo(props.row, 'readonly')}>
                  明细
                </multiuse-button>
                <multiuse-button isShow={Boolean(btnVal)} size="mini" type="text" onClick={() => chooseOrderNo(props.row)}>
                  {btnVal}
                </multiuse-button>
              </div>
            );
          }
        },
        { title: '索赔单号', dataIndex: 'reportNo', sorter: false },
        {
          title: '单据状态',
          dataIndex: 'reportStatus',
          sorter: false,
          filterItems: this.createDictList('5003'),
          dictItems: this.createDictList('5003'),
          render: props => {
            return <span>{this.createDictText(props.row.reportStatus, '5003')}</span>;
          }
        },
        { title: '质量报告主题', dataIndex: 'caseMain', sorter: false },
        { title: 'VIN', dataIndex: 'vin', sorter: false, width: 150 },
        { title: '车牌', dataIndex: 'licensePlate', sorter: false },
        { title: '电机号', dataIndex: 'motorCode', sorter: false },
        { title: '发动机号', dataIndex: 'engineCode', sorter: false },
        { title: '车型', dataIndex: 'modelName', sorter: false },
        { title: '报告人', dataIndex: 'reporter', sorter: false },
        { title: '报告日期', dataIndex: 'applyAt', sorter: true, width: 140 }
      ];
    },
    /**
     * 通过 reportStatus 获取 详情表单状态标识（readonly、add、edit、audit）
     */
    getFromStatus(reportStatus) {
      const { pageType, statusMap } = this
      // code(50031001) => status(edit)
      return statusMap[pageType][String(reportStatus)]
    },
    /**
     * 1.判断第二个按钮是否显示
     * 2.以及第二个操作按钮文案：（审核 || 编辑）
     */
    getBtnValue(item) {
      const { btnValueMap, pageType, getFromStatus } = this
      const { reportStatus } = item

      // code(50031001) => status(edit) => 按钮字(编辑)
      const btnValue = btnValueMap[getFromStatus(reportStatus)]

      // 车  厂 DLR：已提报         才显示第二个按钮 【审核】
      // 经销商 OEM：已提报、已保存   才显示第二个按钮 【编辑】
      let isShow = false;
      let status = []
      status = pageType === 'OEM' ? ['50031001'] : ['50031001', '50031004'];
      isShow = status.includes(String(reportStatus));
      return isShow ? btnValue : null
    },
    /**
     * 设置详情表单状态
     */
    setFromStatus(item, status) {
      console.log(item)
      const { getFromStatus } = this
      const { reportStatus, reportId } = item

      const value = status || getFromStatus(reportStatus)
      // 状态有值才设置
      value && this.setStateParam('editFormStatus', value)
    },
    /**
     * 关闭弹窗
     */
    closeDialog(name) {
      this.isShowDialog[name] = false
      // this.setStateParam('isShowDialog',false)
    },
    /**
     * 修改 store 中的参数 name 为 value
     */
    setStateParam(name, value) {
      const params = { name, value }
      this.SET_STATE_BY_NAME(params)
    },
    /**
     * 新增
     */
    handleAdd() {
      this.setStateParam('editFormStatus', 'add')
      this.editVisible = true;
    },
    /**
     * 车辆选择事件
     */
    handleVehicleChoice(list) {
      console.log('选中的车辆信息=>', list)
      const { setStateParam } = this
      const value = formatDataCarInfo(list[0]) // 取第一个即可（单选）
      // 修改store中的 curEditFormData
      setStateParam('curEditFormData', value)
      // 调用更新逻辑
      this.$nextTick(() => {
        this.$refs.editFormDom.updateForm()
      })
      this.closeDialog('car')
    },
    /**
     * 零件选择事件
     */
    handlePartChoice(list) {
      const { setStateParam, searchPartType } = this
      console.log(searchPartType, '选中的零件信息=>', list)
      const value = formatDataPartInfo(list[0], searchPartType) // 取第一个即可（单选）
      console.log('329', value)
      // 修改store中的 curEditFormData
      setStateParam('curEditFormData', value)
      // 调用更新逻辑
      this.$nextTick(() => {
        this.$refs.editFormDom.updateForm()
      })
      this.closeDialog('part')

      if (searchPartType === 'faultPart') {
        reqSupName({ 'faultPartCode': value.faultPartCode }).then((res) => {
          console.log('supportCode', res.data.supportCode, 'supportName', res.data.supportName);
          setStateParam('curEditFormData', { 'supportCode': res.data.supportCode, 'supportName': res.data.supportName });
          this.$nextTick(() => {
            this.$refs.editFormDom.updateForm()
          })
        });
      }
    },
    onColumnsChange(columns) {
      this.columns = columns;
      this.single = columns.length != 1;
      this.multiple = !columns.length;
    },
    // 导出
    async exportFileBtn() {
      try {
        // let params = { reportNo: "RE202103060001" }
        let params = { ...this.fetchParams }
        let res = await reqExcel(params);
        exportExcelFile(res.data, '质量报告反馈')
      } catch (err) {
        console.warn(err)
      }
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
      console.log(this.selectedRows);
    },
    chooseOrderNo(val, status) {
      // 当前编辑数据
      this.editData = val;
      // 设置表单状态
      this.setFromStatus(val, status)
      this.editVisible = true;
    },
    editClose() {
      this.editVisible = false;
    },
    // 审核操作
    handleAudit(params) {
      this.editVisible = false;
      console.log('审核操作=>', params)
    },
    editSave() {
      this.editVisible = false;
      this.fetchParams = { ...this.fetchParams };
    },
    refreshTable() {
      // console.log(this.$refs.tables)
      this.$refs.tables.DO_REFRESH();
    },
    //搜索获取数据
    changeHandle(val) {
      // if (!val.applyBeginDate) {
      //   this.$notify.warning({ title: '提示信息', message: '查询开始日期不可为空！' });
      //   return;
      // }
      // if (!val.applyEndDate) {
      //   this.$notify.warning({ title: '提示信息', message: '查询结束日期不可为空！' });
      //   return;
      // }
      // if (getAppId() == 'arcfox') {
      //   if (moment(moment(val.applyEndDate).format('YYYY-MM-DD')).diff(moment(val.applyBeginDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '查询日期跨度不可超过十二个月！' });
      //     return;
      //   }
      // } else {
      //   if (moment(moment(val.applyEndDate).format('YYYY-MM-DD')).diff(moment(val.applyBeginDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '查询日期跨度不可超过十二个月！' });
      //     return;
      //   }
      // }
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
      console.log(val);
    }
  }
};
</script>

<style lang="less" scoped></style>
